package com.jiedeng.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jiedeng.controller.Rst;
import com.jiedeng.model.Task;
import com.jiedeng.util.*;
import com.jiedeng.util.httpclient.HttpClientHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 报表管理
 *
 * @author zhouyb
 */
@Controller
@Scope("prototype")
@RequestMapping("/reportManage")
public class ReportManageController {
    @Value("${config.http.client.url}")
    public String url;
    @Autowired
    CommonComponent commonComponent;
    /**
     * 报表管理
     *
     * @param model
     * @param request
     * @return
     * @paramojectId
     */
    @RequestMapping(value = "/reportManageUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String taskManageUI(Model model, String projectId, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
            //model.addAttribute("projectId", projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/report/reportHome";
    }

    /**
     * 查询任务-报表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/taskReportListUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String taskReportListUI(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        try {

            model.addAttribute("ctx", request.getContextPath());
            String httpUrl = url + "/recorder/filterTaskManage?isDelete=false&&taskPersonId=" + SessionUtil.getUserIdSession()
                    + "&&excutePersonId=" + SessionUtil.getUserIdSession() +
                    "&&closePersonId=" + SessionUtil.getUserIdSession() +
                    "&&pubPersonId=" + SessionUtil.getUserIdSession() +
                    "&&verifyPersonId=" + SessionUtil.getUserIdSession();
            String ret = HttpClientHelper.doGet(httpUrl);
            //String ret = HttpClientHelper.postRequest2(url + "/recorder/filterTask", map, "utf-8", "");
            List<Task> taskList = new ArrayList<>();
            if (ret != null) {
                List<Task> list = JSON.parseObject(ret.trim(), new TypeReference<List<Task>>() {
                });

                taskList = getTheCorrespondingTask(list, false, true, false, false, false);
            }
            model.addAttribute("dataUrl", url);
            model.addAttribute("taskList", PageUtil.getTaskPage(taskList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            model.addAttribute("count", taskList.size());
            model.addAttribute("maxPage", taskList.size() / Integer.parseInt(pageSize));
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + taskList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "report/taskReportList";
    }

    /**
     * 查询报表-基础报表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/baseReportListUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String baseReportListUI(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        try {
            Rst rst = commonComponent.checkModuleRule("1040100");
            if(!"OK".equals(rst.getMsg())){
                return ForwardConstants.REDIRECT + "/jurisdictionBlank";
            }
            model.addAttribute("ctx", request.getContextPath());

            //List<Task> taskList = new ArrayList<>();

            model.addAttribute("personId", SessionUtil.getUserIdSession());
            model.addAttribute("dataUrl", url);
            //model.addAttribute("taskList", PageUtil.getTaskPage(taskList, Integer.parseInt(page), Integer.parseInt(pageSize)));
            //model.addAttribute("count", taskList.size());
            //model.addAttribute("maxPage", taskList.size() / Integer.parseInt(pageSize));
            //model.addAttribute("page", page);
            //model.addAttribute("pageSize", pageSize);
            //model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            //model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + taskList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "report/baseReportList";
    }

    /**
     * 跳转上传报表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadReportUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String uploadReportUI(Model model, HttpServletRequest request, String taskId, String subType, String projectId) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            model.addAttribute("dataUrl", url);
            model.addAttribute("taskId", taskId);
            model.addAttribute("subType", subType);
            model.addAttribute("projectId", projectId);
            model.addAttribute("personId", SessionUtil.getUserIdSession());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "report/uploadReport";
    }

    /**
     * 上传报表
     *
     * @param pames
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadReportVersion")
    public String uploadReportVersion(@RequestParam Map<String, String> pames, @RequestParam(value = "file", required = false) MultipartFile file) {
        try {
            String suff = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            if (fileName.indexOf(File.separator) != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
            }
            QiniuUtil qiniuUtil = new QiniuUtil();
            pames.put("reportName", fileName);
            pames.put("type", "1");
            String versionCode = HttpClientHelper.postRequest2(url + "/basicReport/findReportVersionCode", pames, "utf-8", "");
            if(!"1".equals(versionCode)){
                fileName=fileName+"("+(Integer.parseInt(versionCode)-1)+")";
                pames.put("reportName", fileName);
            }
            String reportName =fileName+ "." + suff;
            //PingYinUtil.getPingYin(fileName,"")
                    // + DatetimeUtil.getDateyyyyMMddhhmmss() + ((int) (Math.random() * 100) + 1)
            qiniuUtil.uploadFile(file, reportName);
            pames.put("url", reportName);
            pames.put("versionCode", versionCode);
            pames.put("personId", SessionUtil.getUserIdSession());
            String ret = HttpClientHelper.postRequest2(url + "/basicReport/saveReportVersion", pames, "utf-8", "");

            return ForwardConstants.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 删除版本
     *
     * @param pames
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteReportVersion")
    public String deleteReportVersion(@RequestParam Map<String, String> pames) {
        try {
            String res = HttpClientHelper.doGet(url + "/basicReport/deleteReportVersion?id=" + pames.get("id"));
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return ForwardConstants.ERROR;
        }
    }

    /**
     * 查询报表-明细报表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/detailedReportListUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String detailedReportListUI(Model model, HttpServletRequest request) {
        Rst rst = commonComponent.checkModuleRule("1040200");
        if(!"OK".equals(rst.getMsg())){
            return ForwardConstants.REDIRECT + "/jurisdictionBlank";
        }
        model.addAttribute("ctx", request.getContextPath());
        model.addAttribute("dataUrl", url);
        model.addAttribute("personId", SessionUtil.getUserIdSession());
        return "report/detailedReportList";
    }

    /**
     * 查询报表-统计报表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/statisticsReportListUI", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String statisticsReportListUI(Model model, HttpServletRequest request, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize) {
        try {
            Rst rst = commonComponent.checkModuleRule("1040300");
            if(!"OK".equals(rst.getMsg())){
                return ForwardConstants.REDIRECT + "/jurisdictionBlank";
            }
            model.addAttribute("dataUrl", url);
            model.addAttribute("ctx", request.getContextPath());
            model.addAttribute("personId", SessionUtil.getUserIdSession());
        } catch (Exception e) {
            e.printStackTrace();
        }


        return "report/statisticsReportList";
    }

    /**
     * @param tasks
     * @param isDraft
     * @param isVerify
     * @param isClose
     * @param isCloseDo
     * @param isDo
     * @return
     */
    public List<Task> getTheCorrespondingTask(List<Task> tasks, boolean isDraft, boolean isVerify, boolean isClose, boolean isCloseDo, boolean isDo) {

        List<Task> taskList = new ArrayList<>();
        for (Task task : tasks) {
            taskList.add(task);
        }
        return taskList;
    }
}
